const { DataTypes } = require('sequelize');
const sequelize = require('@shared/utils/database');
const crypto = require('crypto');

const Admin = sequelize.define('Admin', {
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    comment: '管理员ID'
  },
  username: {
    type: DataTypes.STRING(32),
    allowNull: false,
    comment: '用户名',
    validate: {
      notEmpty: true,
      len: [2, 32]
    }
  },
  password: {
    type: DataTypes.STRING(32),
    allowNull: false,
    comment: '密码',
    validate: {
      notEmpty: true,
      len: [6, 32]
    },
    set(value) {
      // 使用MD5加密
      const md5 = crypto.createHash('md5');
      const hash = md5.update(value).digest('hex');
      this.setDataValue('password', hash);
    }
  },
  name: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '姓名'
  },
  phone: {
    type: DataTypes.STRING(11),
    allowNull: true,
    comment: '手机号',
    validate: {
      is: /^1[3-9]\d{9}$/
    }
  },
  status: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 1,
    comment: '状态：0-禁用 1-正常'
  },
  last_login_time: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '最后登录时间'
  }
}, {
  tableName: 'admin',
  timestamps: true,
  createdAt: 'create_time',
  updatedAt: 'update_time',
  indexes: [
    {
      unique: true,
      fields: ['username']
    }
  ]
});

// 密码验证方法
Admin.prototype.comparePassword = function(password) {
  const md5 = crypto.createHash('md5');
  const hash = md5.update(password).digest('hex');
  return this.password === hash;
};

module.exports = Admin; 